import React from "react";
import { setPlayHistory } from "@/helpers/localStorage";
import {
  HTMLMediaState,
  HTMLMediaControls,
} from "@/hooks/utils/createHTMLMediaHook";
export interface IState {
  musicId: number;
  musicUrl: string;
  picUrl: string;
  musicName: string;
  song: string;
  autoPlay: boolean;
}

export interface IAction {
  type: string;
  paLoad: IDictionary<any>;
}

interface playState {
  playState: boolean;
}

export const initialState = {
  musicId: 0,
  musicUrl: "",
  picUrl: "",
  musicName: "",
  song: "",
  autoPlay: false,
};

export const getMusicUrl = (id?: number): string => {
  return id ? `https://music.163.com/song/media/outer/url?id=${id}.mp3` : "";
};

const playMusicReducer = (state: IState, action: IAction) => {
  switch (action.type) {
    case "PLAY": {
      if (!action.paLoad.keepOrder) {
        // console.log("设置播放历史");
        setPlayHistory({
          musicId: action.paLoad.musicId,
          picUrl: action.paLoad.picUrl,
          musicName: action.paLoad.musicName,
          song: action.paLoad.song,
        });
      }
      return {
        ...state,
        musicId: action.paLoad.musicId,
        // musicUrl: getMusicUrl(action.paLoad.musicId),
        musicUrl: action.paLoad.musicUrl,
        picUrl: action.paLoad.picUrl,
        musicName: action.paLoad.musicName,
        song: action.paLoad.song,
        autoPlay: action.paLoad.autoPlay,
      };
    }
    default:
      return state;
  }
};

export default playMusicReducer;

export interface IAudioContext {
  audio?: React.ReactElement | null;
  state?: HTMLMediaState;
  controls?: HTMLMediaControls;
  ref?: {
    current: HTMLAudioElement | null;
  };
  playState?: playState;
  duration?: number;
  currentTime?: number;
}

// 创建context
export const PlayMusicStateContext = React.createContext(initialState);
export const playMusicDispatchContext = React.createContext<
  React.Dispatch<IAction>
>(() => {});
export const AudioContext = React.createContext<IAudioContext>({});
